﻿using System;
using System.Windows;
using System.Windows.Controls;
using BingleMaps.Models;
using BingleMaps.Services;
using Microsoft.Phone.Controls;

namespace BingleMaps.Controls
{
	public class UserPushpinContent : Control
	{
		public event EventHandler<System.Windows.Input.GestureEventArgs> FromButtonTap, ToButtonTap, DeleteButtonTap, PinButtonTap;
		private UserPin _userPin;

		public UserPushpinContent()
		{
			DefaultStyleKey = typeof(UserPushpinContent);
		}

		public override void OnApplyTemplate()
		{
			((CaptionButton)GetTemplateChild("FromButton")).Tap += FromButtonTap;
			((CaptionButton)GetTemplateChild("ToButton")).Tap += ToButtonTap;
			((CaptionButton)GetTemplateChild("DeleteButton")).Tap += DeleteButtonTap;
			((CaptionButton)GetTemplateChild("PinButton")).Tap += PinButtonTap;
			((UIElement)GetTemplateChild("ContentPanel")).Tap += (s, e) => e.Handled = true;

			_userPin = DataContext as UserPin;

			if (_userPin == null) return;
			if (_userPin.Address == null) BingMapsServices.GetAddress(_userPin.Location, result =>
			{
				if (result != null) _userPin.Address = result.Address.FormattedAddress;
			});

			VisualStateManager.GoToState(this, IsExpanded ? "Expanded" : "Collapsed", true);
			GestureService.GetGestureListener(this).Hold += (s, e) => e.Handled = true;
		}

		public bool IsExpanded
		{
			get { return (bool)GetValue(IsExpandedProperty); }
			set { SetValue(IsExpandedProperty, value); }
		}

		public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register(
			"IsExpanded",
			typeof(bool),
			typeof(UserPushpinContent),
			new PropertyMetadata(false, (s, e) => VisualStateManager.GoToState((UserPushpinContent)s, (bool)e.NewValue ? "Expanded" : "Collapsed", true)));
	}
}
